package com.tao.china.common.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.log4j.Logger;


/**
 * 数据库Utility类.
 * <p>
 * 获取数据库连接池.
 * </p>
 * 
 * 
 */
public abstract class DbUtil {
    /**
     * 表示日志.
     */
    private static final Logger logger = Logger.getLogger(DbUtil.class);
    private static String driverClassName = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/fanyi";
    private static String username = "root";
    private static String password = "156456";
    private static String maxActive = "30";
    private static String maxIdle = "10";
    private static String maxWait = "1000";
    private static String removeAbandoned = "false";
    private static String removeAbandonedTimeout = "120";
    private static String testOnBorrow = "true";
    private static String logAbandoned = "true";

    private static DataSource dataSource = buildBasicdataSource();


    private static DataSource buildBasicdataSource() {

        Properties p = new Properties();
        p.setProperty("driverClassName", driverClassName);
		  p.setProperty("url", url);
		  p.setProperty("password", password);
		  p.setProperty("username", username);
		  p.setProperty("maxActive", maxActive);
		  p.setProperty("maxIdle", maxIdle);
		  p.setProperty("maxWait", maxWait);
		  p.setProperty("removeAbandoned", removeAbandoned);
		  p.setProperty("removeAbandonedTimeout", removeAbandonedTimeout);
		  p.setProperty("testOnBorrow", testOnBorrow);
		  p.setProperty("logAbandoned", logAbandoned);
		logger.info("connect db using: " + p.getProperty("url"));

        DataSource ds = null;
        try {
            ds = BasicDataSourceFactory.createDataSource(p);
        } catch (Exception ex) {
            logger.error("buildBasicdataSource", ex);
        }
        return ds;
    }

    /**
     * 获取数据库连接.
     * 
     * @return 数据库连接.
     * @throws SQLException
     *             如果有数据库异常.
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 关闭数据库连接
     * 
     * @param conn
     * @param st
     * @param rs
     */
    public static void close(final Connection conn, final Statement st, final ResultSet rs) {
        try {
            if (null != rs) {
                rs.close();
            }
            if (null != st) {
                st.close();
            }
            if (null != conn) {
                conn.close();
            }
        } catch (Exception ex) {
            logger.error("close db conn, rs causes inner exception", ex);
        }
    }
}
